<template>
	<view>
		<t-form class="p-5" ref="form" validateTrigger="manual">
			<t-field name="status" label="歌单状态" labelIcon="pic-left">
				<t-switch v-model="formData.status" color="base" />
			</t-field>
			<t-field required name="listName" label="歌单名称" labelIcon="deleteuser">
				<t-input size="w-50" color="base" v-model="formData.listName" placeholder="请输入歌单名称" />
			</t-field>
			<t-field required name="listPoster" label="歌单封面" labelIcon="deleteuser">
				<view class="flex w-85">
					<t-input size="flex-1 w-80" color="base" v-model="formData.listPoster" placeholder="请上传歌单封面" />
					<t-btn size="w-20 h-6 ml-5 text-md" @click="uploadPoster">选择上传</t-btn>
					<t-btn size="w-20 h-6 ml-5 text-md" @click="uploadPoster">媒体库</t-btn>
				</view>

			</t-field>
			<t-field name="description" label="歌单介绍" labelIcon="file-text">
				<t-textarea color="base" size="w-78 h-20" v-model="formData.description" :placeholder="description" />
			</t-field>
			<t-field name="checkGroup" label="风格类别" labelIcon="check-square">
				<unicloud-db v-slot:default="{data, loading, error, options}" collection="my-music-styles" gettree>
					<view v-if="error">{{error.message}}</view>
					<view v-else class="flex w-full mb-5">
						<view class="" v-for="(item,index) in data" :key="index">
							<view class="mr-3 yueqiParent" @click="checkboxChange(item._id)">
								{{item.name}}
								<t-icon :type="[formData.style_ids.includes(item._id)?'check-square':'border' ]" />
								<view class="yuqiChild ml-1 text-md text-base flex ">
									<view v-for="(child,cindex) in item.children"
										@click.stop="checkboxChange(child._id)">
										{{child.name}}
										<t-icon
											:type="[formData.style_ids.includes(child._id)?'check-square':'border' ]" />
									</view>
								</view>
							</view>
						</view>
					</view>
				</unicloud-db>
			</t-field>
			<t-field name="checkGroup" label="乐器类别" labelIcon="check-square">
				<unicloud-db v-slot:default="{data, loading, error, options}" collection="my-music-categories" gettree>
					<view v-if="error">{{error.message}}</view>
					<view v-else class="flex">
						<view class="" v-for="(item,index) in data" :key="index">
							<view class="mr-3 yueqiParent" @click="checkCategory(item._id)">
								{{item.name}}
								<t-icon :type="[formData.category_ids.includes(item._id)?'check-square':'border' ]" />
								<view class="yuqiChild ml-1 text-md text-base flex ">
									<view v-for="(child,cindex) in item.children"
										@click.stop="checkCategory(child._id)">
										{{child.name}}
										<t-icon
											:type="[formData.category_ids.includes(child._id)?'check-square':'border' ]" />
									</view>
								</view>
							</view>

						</view>
					</view>
				</unicloud-db>
			</t-field>
			<!-- 歌曲列表显示区 -->
			<t-field name="checkGroup" label="歌曲列表" labelIcon="check-square">
				<t-btn size="w-20 h-6 ml-5 mb-3 text-md" @click="open('close-circle')">点击选择</t-btn>
				<view class="w-78">
					<view class="" v-for="(music,index) in formData.music_array" :key="index">
						{{music.title}}
						<t-icon class="ml-3" type="close-circle" color="error"
							@click="formData.music_array.splice(index,1)" />
					</view>
				</view>

			</t-field>
		</t-form>
		<!-- 选择音乐弹出层 -->
		<t-popup v-model="visible" :closeIcon="closeIcon" rounded="md">
			<view class="p-5">
				<view class="flex mb-3 mt-3 justify-center items-center">
					<t-search size="xs" @leftIconClick="onKeyInput" @click="searchClick" @confirm="searchConfirm"
						v-model="searchValue" color=" " rounded="full" shadow="sm" leftIcon="shopping"
						clearIcon="close" />
					<t-btn class="ml-3" @click="searchAc" size="sm" ghost rounded="full">GO</t-btn>
				</view>
				<unicloud-db ref="myudb" v-slot:default="{data, loading, error, options}" field="title"
					collection="my-music" :where="searchWhere" loadtime="manual">
					<view v-if="error">{{error.message}}</view>
					<view v-else>
						<view class="" v-for="(item,index) in data" :key="index" @click="checkMusic(item)">
							{{item.title}}
							<t-icon :type="[formData.music_array.includes(item)?'check-square':'border' ]" />
						</view>
					</view>
				</unicloud-db>
			</view>
		</t-popup>
		<view class="mt-5 pb-10 text-center">
			<t-btn color="base" size="w-45" @click="submit">提交</t-btn>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				listId: '',
				itemTemp: {},
				searchValue: '',
				visible: false,
				closeIcon: '',
				mode: 'center',
				formData: {
					listName: '',
					listPoster: '',
					description: '',
					style_ids: [],
					category_ids: [],
					music_array: [],
					status: true
				}
			}
		},
		onLoad(e) {
			console.log(e.id)
			this.listId = e.id
			const db = uniCloud.database()
			db.collection('my-music-songlist,my-music').where({
					_id: e.id
				})
				.field('listName,listPoster,description,status,style_ids,category_ids,music_array._id,music_array.title')
				.get({
					getOne: true
				})
				.then(res => {
					console.log(res.result);
					this.formData = res.result.data
				}).catch(err => {
					console.error(err)
				})
		},
		computed: {
			searchWhere() {
				return `${new RegExp(this.searchValue, 'i')}.test(title)` // 使用计算属性得到完整where
			},
			hasItem() {
				let res = -1
				if (this.formData.music_array.length > 0) {
					this.formData.music_array.forEach((item, index) => {
						if (item._id == this.itemTemp._id) {
							// console.log('111111111111重复')
							res = index
						}
					})
				}
				return res
			}
		},
		mounted() {
			const rules = {
				listName: [
					field => {
						if (!field.value) {
							return `${field.label}必填`
						}
					}
				],
				status: [
					field => field.value || `${field.label}必须打开`
				],
			}
			this.$refs.form.setRules(rules)
		},
		methods: {
			searchAc() {
				console.log(this.searchValue)
				this.$refs.myudb.clear()
				setTimeout(() => {
					this.$refs.myudb.loadData()
				}, 300)

			},
			open(type) {
				// this.mode = type
				this.closeIcon = type
				this.visible = true
			},
			uploadPoster() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						console.log(res.tempFiles[0].name);
						if (res.tempFilePaths.length > 0) {
							let filePath = res.tempFilePaths[0]
							//进行上传操作
							uniCloud.uploadFile({
								filePath: filePath,
								cloudPath: res.tempFiles[0].name,
								onUploadProgress: function(progressEvent) {
									console.log(progressEvent);
									var percentCompleted = Math.round(
										(progressEvent.loaded * 100) / progressEvent.total
									);
								},
								success: (e) => {
									this.formData.listPoster = e.fileID
									console.log(e.fileID)
								},
								fail() {},
								complete() {}
							});

						}
					}
				});
			},
			async submit() {
				// 手动调用校验，返回 res 可查看各个域的校验结果
				const res = await this.$refs.form.validateAll()

				// results.status 校验成功与否
				// results.fields 具体域的校验情况
				if (this.formData.style_ids.length == 0) {
					uni.showToast({
						title: '请选择分类',
						icon: 'error'
					})
					return
				}
				// 简单实现一下深拷贝JSON.parse(JSON.stringify(this.formData))
				let postData = JSON.parse(JSON.stringify(this.formData))
				const tempArray = []
				postData.music_array.forEach((item) => {
					tempArray.push(item._id)
				})
				postData.music_array = tempArray
				delete postData._id
				// return
				const db = uniCloud.database()
				uni.showLoading({

				})
				db.collection('my-music-songlist').where({
						_id: this.listId
					}).update(postData)
					.then(res => {
						console.log(res.result)
						uni.hideLoading()
						uni.navigateTo({
							url: '/uni_modules/uniapper-music-admin/pages/songlist/list',
							animationType: 'zoom-fade-out',
							animationDuration: 2000
						})
					}).catch(err => {
						console.error(err)
					})

			},
			udbload(data) {
				console.log(data)
			},
			checkboxChange(e) {
				console.log(e)
				if (this.formData.style_ids.includes(e)) {
					// console.log("已添加过")
					const findRes = this.formData.style_ids.findIndex((ee) => e == ee)
					this.formData.style_ids.splice(findRes, 1)
				} else {
					this.formData.style_ids.push(e)
				}
			},
			checkCategory(e) {
				console.log(e)
				if (this.formData.category_ids.includes(e)) {
					// console.log("已添加过")
					const findRes = this.formData.category_ids.findIndex((ee) => e == ee)
					this.formData.category_ids.splice(findRes, 1)
				} else {
					this.formData.category_ids.push(e)
				}
			},
			checkMusic(e) {
				console.log(JSON.stringify(e))
				this.itemTemp = e
				console.log(this.hasItem)
				if (this.hasItem >= 0) {
					this.formData.music_array.splice(this.hasItem, 1)
					return
				}
				this.formData.music_array.push(e)
			}
		}

	}
</script>

<style scoped lang="less">
	.content {}

	.yueqiParent {
		position: relative;
		height: 2rem;
		max-width: 100%;
	}

	.yueqiParent:hover .yuqiChild {
		display: flex;
	}

	.yuqiChild {
		position: absolute;
		z-index: 999;
		top: 1.5rem;
		left: 0;
		display: none;
		flex-wrap: wrap;
		width: 30rem;
	}

	.yuqiChild view {
		width: 7rem;
	}
</style>
